﻿using System;
using System.Text.RegularExpressions;
using ManoMachine.Assembler.Exceptions;
using ManoMachine.Assembler.Parsers;

namespace ManoMachine.Assembler.Mnemonics.Descriptors
{
    class MRIDescriptor : InstructionDescriptor
    {
        public MRIDescriptor(string name, ushort hexCode)
            : base(name, hexCode)
        {
        }

        public override bool IsValidInstruction(AssemblyLine assemblyLine)
        {
            if ((assemblyLine.InstructionParts.Length != 2) && (assemblyLine.InstructionParts.Length != 3))
                return false;

            string symbolicAddress = assemblyLine.InstructionParts[1];
            MatchCollection matchCollection = Regex.Matches(symbolicAddress, "[a-zA-Z][a-zA-Z0-9]?[a-zA-Z0-9]?");
            if (matchCollection.Count != 1 || matchCollection[0].Index != 0 || matchCollection[0].Length != symbolicAddress.Length)
            {
                throw new AssemblerException("invalid symbolic address", assemblyLine);
            }
            
            if (assemblyLine.InstructionParts.Length==3 && string.Compare(assemblyLine.InstructionParts[2], "I", true)!=0 )
            {
                throw new AssemblerException("invalid directive 'I' letter is expected here", assemblyLine);
            }

            return true;
        }

        /// <summary>
        /// IsValidInstruction() MUST BE called before this function.
        /// </summary>
        /// <param name="assemblyLine"></param>
        /// <returns></returns>
        public string GetSymbolicAddress(AssemblyLine assemblyLine)
        {
            return assemblyLine.InstructionParts[1];
        }

        /// <summary>
        /// IsValidInstruction() MUST BE called before this function.
        /// </summary>
        /// <param name="assemblyLine"></param>
        /// <returns></returns>
        public bool GetIndirectMemory(AssemblyLine assemblyLine)
        {
            return assemblyLine.InstructionParts.Length == 3;
        }
    }
}